﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Windows.Storage;

namespace Coder.Framework
{
    /// <summary>
    /// Provides static generalized access and editing of Roaming Files using the Windows 8 API.
    /// </summary>
    public class FileAccess<T>
    {
        /// <summary>
        /// Serializes an object into the Roaming Folder of the Windows 8 User Account.
        /// </summary>
        /// <param name="toSerialize">The object to be serialized.</param>
        /// <param name="fileLocation">The location of the serialization.</param>
        public static async Task SaveFile(T toSerialize, string fileLocation)
        {
            StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder; //Gets the roaming folder that exists within the Metro Roaming Data.

            StorageFile sampleFile = await roamingFolder.CreateFileAsync(fileLocation, CreationCollisionOption.ReplaceExisting); //Creates or replaces the xml doc.

            XmlSerializer xml = new XmlSerializer(typeof(T)); //Creates a Serializable Object with this current object as a template, via the inherited method from the Object class, GetType().

            StringBuilder builder = new StringBuilder();
            XmlWriter xmlWriter = XmlWriter.Create(builder);
            xml.Serialize(xmlWriter, toSerialize);

            await FileIO.WriteTextAsync(sampleFile, builder.ToString());
        }

        /// <summary>
        /// Loads an object from the Roaming Folder of the Windows 8 User Account.
        /// </summary>
        /// <param name="fileLocation">Location of the file to be serialized.</param>
        public static async Task<T> LoadFile(string fileLocation)
        {
            StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder;
            StorageFile file = await roamingFolder.GetFileAsync(fileLocation);

            string xmlDocText = await FileIO.ReadTextAsync(file);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            XmlReaderSettings settings = new XmlReaderSettings();
            StringReader reader = new StringReader(xmlDocText);

            XmlReader xmlReader = XmlReader.Create(reader);

            return (T)xmlSerializer.Deserialize(xmlReader);
        }

    }
}